<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="{{ settings.SITE_STATIC_URL }}/assets/vue/bk-magic-vue.min.css">
    <title>BCS Console Mgr</title>
    <style type="text/css">
        .bk-notify {
            padding: 9px 15px;
        }

        .console-iframe {
            width: 100%;
            height: 100%;
            border: none;
            background: #000;
        }

        .bk-tab-section {
            border: none;
        }

        .bk-tab-content {
            background: #000;
            padding: 0;
        }

        .bk-tab-section {
            padding: 0;
        }

        .close {
            width: 24px;
            height: 24px;
            text-align: center;
            line-height: 24px;
            display: inline-block;
            font-style: normal;
            font-size: 12px;
            background: #eee;
            border-radius: 50%;
            overflow: hidden;
            vertical-align: middle;
            margin-left: 10px;
            color: #999;
            cursor: pointer;
            transform: scale(0.9);
        }

        #app .bk-dropdown-menu {
            display: inline-block;
            position: relative;
            position: absolute;
            left: 0;
            top: 42px;
            z-index: 1000;
            background: #fff;
            width: 200px;
        }

        .bk-tab-label-wrapper .bk-tab-label-list .bk-tab-label-item {
            min-width: 200px;
        }

        [v-cloak] {
            display: none;
        }

        .mask {
            width: 100%;
            height: 100%;
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            z-index: 1;
            opacity: 0;
        }

        .bk-tab-label-wrapper .bk-tab-label-list .bk-tab-label-item .bk-tab-close-controller {
            position: absolute;
            right: 10px;
            top: 13px;
        }

        .bk-tab-label-wrapper .bk-tab-label-list .bk-tab-label-item.active .bk-tab-label {
            font-weight: bold;
            color: #3a84ff;
        }

        .bk-tab-label-wrapper .bk-tab-label-list .bk-tab-label-item.active .panel-count {
            background-color: #3a84ff;
        }

        .bk-dropdown-menu .bk-dropdown-list>li>a.selected {
            background: #ebf4ff;
            color: #3c96ff
        }

        .panel-count {
            position: absolute;
            left: 10px;
            top: 13px;
            width: 16px;
            height: 16px;
            padding: 0 4px;
            line-height: 16px;
            border-radius: 2px;
            text-align: center;
            font-style: normal;
            font-weight: normal;
            font-size: 12px;
            color: #fff;
            background-color: #C4C6CC;
            display: inline-block;
            margin-left: 3px;
        }

        .bk-dropdown-menu {
            opacity: 0;
            transition: opacity ease 0.3s;
        }
    </style>
</head>

<body style="background-color: #000;">
    <div id="app">
        <input type="text" id="short-focus" style="opacity: 0; position: absolute; z-index: 0;" @keyup="handleInput" />
        <bk-tab addable :active.sync="active" :closable="closable" @add-panel="showDropdown" @close-panel="closePanel"
            @tab-change="handleTabChange" v-bk-clickoutside="handleClick">
            <bk-tab-panel v-for="(panel, index) in panels" v-bind="panel" :key="index">
                <template slot="label">
                    <i class="panel-count">$[index + 1]</i>
                    <span class="panel-name">$[panel.label]</span>
                </template>
                <iframe @click="handleClick" :src="panel.url" class="console-iframe"
                    :style="{width: `${winWidth - 40}px`, height: `${winHeight - 100}px`}"></iframe>
            </bk-tab-panel>
        </bk-tab>
        <div class="mask" v-show="isDropdownShow"></div>
        <div class="bk-dropdown-menu" :style="{left: `${dropdownLeft}px`, opacity: (isDropdownShow ? 1 : 0)}" v-cloak
            v-show="isDropdownShow">
            <div class="bk-dropdown-content right-align is-show" v-cloak>
                <ul class="bk-dropdown-list">
                    <li>
                        <a href="javascript:;" v-cloak :class="{selected: index === selectIndex}"
                            @click.stop.prevent="addTerminal(cluster)"
                            v-for="(cluster, index) of clusterList">$[cluster.name]</a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <script src="{{ settings.SITE_STATIC_URL }}/assets/vue/vue.js"></script>
    <script src="{{ settings.SITE_STATIC_URL }}/assets/vue/bk-magic-vue.min.js"></script>
    <script src="{{ settings.SITE_STATIC_URL }}/assets/jquery.min.js"></script>
    <script type="text/javascript" defer>
        var app = new Vue({
            delimiters: ['$[', ']'],
            el: '#app',
            data: {
                tabIndex: 0,
                panels: [],
                active: '',
                winWidth: 1270,
                winHeight: 500,
                projectId: '',
                siteUrl: '',
                dropdownLeft: 0,
                isDropdownShow: false,
                clusterList: [],
                selectIndex: -1
            },
            computed: {
                closable() {
                    return this.panels.length > 1
                }
            },
            mounted() {
                this.init()
            },
            methods: {
                init() {
                    this.winWidth = $(window).width()
                    this.winHeight = $(window).height()

                    $(window).resize(function () {
                        this.winWidth = $(window).width()
                        this.winHeight = $(window).height()

                    })

                    // const params = this.parseUrlQuery()
                    const url = window.location.href
                    const reg = /projects\/([\w\d]*)\/mgr\/#cluster=([\w\d-]*)/
                    const matcher = url.match(reg)

                    if (matcher) {
                        this.projectId = matcher[1]
                        this.watchMessage()
                        this.watchShortcut()

                        const cluster_url = '{{ settings.DEVOPS_BCS_API_URL }}/api/projects/{{ project_id }}/clusters?limit=1000'
                        self = this
                        $.getJSON(cluster_url, function (result) {
                            self.clusterList = result.data.results
                            self.openTab({
                                clusterId: matcher[2]
                            })
                        })
                    }
                },
                handleClick() {
                    this.isDropdownShow = false
                    this.isSelectIndex = -1
                },
                handleTabChange(name) {
                    console.log(name)
                    const panel = this.panels.find(item => {
                        return item.name === name
                    })
                    if (panel) {
                        window.location.hash = `cluster=${panel.clusterId}`
                    }
                },
                handleInput(event) {
                    const len = this.clusterList.length
                    if (event.key === 'ArrowDown') {
                        if (this.selectIndex < len) {
                            this.selectIndex++
                        } else {
                            this.selectIndex = 0
                        }
                    } else if (event.key === 'ArrowUp') {
                        if (this.selectIndex > -1) {
                            this.selectIndex--
                        } else {
                            this.selectIndex = len - 1
                        }
                    } else if (event.key === 'Enter') {
                        const cluster = this.clusterList[this.selectIndex]
                        if (!cluster) return
                        this.addTerminal(cluster)
                        this.isDropdownShow = false
                        this.selectIndex = -1
                    }
                },
                parseUrlQuery() {
                    const obj = {}
                    let keyvalue = []
                    let url = window.location.href
                    let key = ''
                    let value = ''
                    let paraString = url.substring(url.indexOf('?') + 1, url.length).split('&')

                    for (const i in paraString) {
                        keyvalue = paraString[i].split('=')
                        key = keyvalue[0]
                        value = keyvalue[1]
                        obj[key] = value
                    }
                    return obj
                },
                openTab(data) {
                    if (!data.clusterId) return
                    const self = this
                    const clusterId = data.clusterId
                    let clusterName = 'default'
                    const siteUrl = data.siteUrl
                    const url = `{{ settings.DEVOPS_BCS_API_URL }}/web_console/projects/{{ project_id }}/clusters/${clusterId}/?source=mgr`

                    const tabKeys = self.panels.map(item => {
                        return item.name
                    })

                    this.clusterList.forEach(item => {
                        if (item.cluster_id === clusterId) {
                            clusterName = item.name
                        }
                    })
                    this.tabIndex++
                    self.panels.push({
                        name: clusterId + this.tabIndex,
                        clusterId: clusterId,
                        label: clusterName,
                        url: url
                    })
                    self.active = clusterId + this.tabIndex
                    window.location.hash = `cluster=${clusterId}`
                    this.isDropdownShow = false
                    this.selectIndex = -1
                },
                watchMessage() {
                    const self = this
                    window.addEventListener('message', function (event) {
                        const data = event.data
                        if (data.type === 'shortcut' && data.key === 'showDropdown') {
                            self.showDropdown()
                            self.$nextTick(function () {
                                $('#short-focus').focus()
                            })
                        } else if (data.type === 'shortcut' && data.key === 'activeTab') {
                            self.activeTab(data.value)
                        } else {
                            self.openTab(data)
                        }
                    })
                },
                watchShortcut() {
                    const self = this
                    $(window).keydown(function (event) {
                        // open dropdown
                        if (event.altKey && event.keyCode === 78) {
                            self.showDropdown()
                        } else if (event.altKey && (event.keyCode >= 49 && event.keyCode <= 57)) {
                            // open 1-9 tab
                            self.activeTab(event.keyCode)
                        }
                    })
                },
                activeTab(code) {
                    const index = parseInt(String.fromCharCode(code)) - 1
                    if (this.panels[index]) {
                        this.active = this.panels[index].name
                        window.location.hash = `cluster=${this.panels[index].clusterId}`
                        this.$nextTick(function () {
                            $('#short-focus').focus()
                        })
                    }
                },
                closePanel(index, panel) {
                    this.panels.splice(index, 1)
                    if (this.panels.length) {
                        this.active = this.panels[0].name
                        window.location.hash = `cluster=${this.panels[0].clusterId}`
                    }
                    this.$bkNotify({
                        theme: 'primary',
                        offsetY: 1,
                        delay: 3000,
                        message: `【${index + 1}】${panel.label} 连接已经断开`
                    })
                    this.isDropdownShow = false
                    this.selectIndex = -1
                },
                showDropdown() {
                    let left = $('.bk-tab-add-controller').offset().left
                    if ((left + 200) > this.winWidth) {
                        this.dropdownLeft = left - 200
                    } else {
                        this.dropdownLeft = left
                    }
                    this.isDropdownShow = true
                    this.$nextTick(function () {
                        $('#short-focus').focus()
                    })
                },
                addTerminal(cluster) {
                    this.openTab({
                        projectId: this.projectId,
                        siteUrl: this.siteUrl,
                        clusterId: cluster.cluster_id,
                        clusterName: cluster.name
                    })
                    this.isDropdownShow = false
                    this.isSelectIndex = -1
                }
            }
        })

    </script>
</body>

</html>